# -*- coding: utf-8 -*-
# from __future__ import unicode_literals
from demo.config import maxSize,wordDir,customInfoDir,customInfoDirTemp
from django.shortcuts import render_to_response,render
from django.http import HttpResponse,StreamingHttpResponse
from marsAux.md5Handler import getMd5
from marsAux.dirHandler import makeDir
from marsAux.word2txt import Word2Txt
from marsAux.zipHandler import ZipUtilities
from django.core.cache import cache
from wsgiref.util import FileWrapper
from marsAux.unitHandler import qq,email,address,mobilphone,telphone,url,weichat,otherHandle,companyName

import logging
import chardet
import time
import shutil
import xlwt
import os,tempfile,zipfile
import json

# Create your views here.
logger = logging.getLogger("django")
def index(request):
    logger.warning("qing qiu page......")
    return render_to_response('marsplan/uploadfile.html')

def customuploadhandle(request):
    # 先获取自定义分割文件
    if request.method == "POST":    # 请求方法为POST时，进行处理
        catalogFile =request.FILES.get("customfile", None)    # 获取上传的文件，如果没有文件，则默认为None
        contentFile =request.FILES.get("contentfile", None)    # 获取上传的文件，如果没有文件，则默认为None
        if not catalogFile:
            return HttpResponse("请选择目录文件上传！")
        if not contentFile:
            return HttpResponse("请选择内容文件上传！")

        if contentFile.size > 1024*1024*maxSize:
            return HttpResponse("上传的文件大小不能超过100M")
        txtContent=catalogFile.read()
        fileCharInfo=chardet.detect(txtContent)['encoding']
        res=txtContent.decode(fileCharInfo).split('\n')   #目录中每一个标志行,res里面每行内容的编码是unicode
        catalog={}
        count=1
        for each in res:
            each=each.strip()
            if len(each)==0:
                continue
            else:
                temp=[]
                temp.append(each)
                temp.append(getMd5(each))
                catalog[str(count)]=temp
                count+=1
        #对上传内容进行处理、存储
        name=contentFile.name.split(".")
        filenameMd5=getMd5(name[0]+unicode(time.time()))  #文件名md5
        filename=filenameMd5+u"."+name[-1]   #文件名md5+后缀
        destination = open(os.path.join(wordDir,filename),'wb+')    # 打开特定的文件进行二进制的写操作
        for chunk in contentFile.chunks():      # 分块写入文件
            destination.write(chunk)
        destination.close()

    makeDir(customInfoDir,filenameMd5)   #一个word文件对应一个txt文档
    customsegmentInfo(filename,filenameMd5,catalog) #进行分片并获取信息

    # 把信息写到cache中
    catalogJson=json.dumps(catalog)
    cache.set(filenameMd5,catalogJson,600)
    return render_to_response('marsplan/transition.html',{'filenameMd5':filenameMd5})

def customsegmentInfo(fileName,parentDirMd5,catalog):
    w2t=Word2Txt()
    # w2t.word2CompanyInfoSegment(wordDir+"\\",fileName,parentDirMd5)
    w2t.word2CustomInfoSegmen(wordDir+"\\",fileName,parentDirMd5,catalog)

def customBuildInfoResult(wordFileMd5):
    wordDir=customInfoDir
    targetDir=wordDir+"\\"+wordFileMd5
    manyCompanyDir=os.listdir(targetDir)

    result=[]
    for eachDir in manyCompanyDir:
        eachCompanyDir=targetDir+"\\"+eachDir
        fileList=os.listdir(eachCompanyDir)      #表示一个数据块中有多少个联系方式单元
        # if len(fileList)<5:        #每一个单元模块都会有fullInfo.txt，联系单元种类阈值设置为3
        #     continue
        qqL=qq(eachCompanyDir,fileList,eachDir)
        emailL=email(eachCompanyDir,fileList,eachDir)
        # 地址仅仅识别一个
        addressL=address(eachCompanyDir,fileList,eachDir)
        mobilphoneL=mobilphone(eachCompanyDir,fileList,eachDir)
        telphoneL=[]
        Temp=telphone(eachCompanyDir,fileList,eachDir)
        telphoneL+=Temp[0]
        mobilphoneL+=Temp[1]


        urlL=url(eachCompanyDir,fileList,eachDir)
        weichatL=weichat(eachCompanyDir,fileList,eachDir)
        # --------------------------------------------------------
        otherRes=otherHandle(eachCompanyDir,fileList,eachDir)

        emailL+=otherRes['email']
        addressL+=otherRes['address']
        urlL+=otherRes['url']
        mobilphoneL+=otherRes['mobilphone']
        telphoneL+=otherRes['telphone']
        res={}
        res['qq']=showOne(qqL)
        res['email']=showOne(emailL)
        res['address']=showOne(addressL)
        res['mobilphone']=showOne(mobilphoneL)
        res['telphone']=showOne(telphoneL)
        res['url']=showOne(urlL)
        res['weichat']=showOne(weichatL)
        result.append(res)
    return result

def customBuildDetailInfo(wordFileMd5):
    wordDir=customInfoDir
    targetDir=wordDir+"\\"+wordFileMd5
    manyCompanyDir=os.listdir(targetDir)

    result=[]
    for eachDir in manyCompanyDir:
        eachCompanyDir=targetDir+"\\"+eachDir
        fileList=os.listdir(eachCompanyDir)      #表示一个数据块中有多少个联系方式单元
        # if len(fileList)<5:        #每一个单元模块都会有fullInfo.txt，联系单元种类阈值设置为3
        #     continue
        qqL=qq(eachCompanyDir,fileList,eachDir)
        emailL=email(eachCompanyDir,fileList,eachDir)
        # 地址仅仅识别一个
        addressL=address(eachCompanyDir,fileList,eachDir)
        mobilphoneL=mobilphone(eachCompanyDir,fileList,eachDir)
        telphoneL=[]
        Temp=telphone(eachCompanyDir,fileList,eachDir)
        telphoneL+=Temp[0]
        mobilphoneL+=Temp[1]


        urlL=url(eachCompanyDir,fileList,eachDir)
        weichatL=weichat(eachCompanyDir,fileList,eachDir)
        # --------------------------------------------------------
        otherRes=otherHandle(eachCompanyDir,fileList,eachDir)

        emailL+=otherRes['email']
        addressL+=otherRes['address']
        urlL+=otherRes['url']
        mobilphoneL+=otherRes['mobilphone']
        telphoneL+=otherRes['telphone']

        res={}
        res['qq']=set(qqL)
        res['email']=set(emailL)
        res['address']=set(addressL)
        res['mobilphone']=set(mobilphoneL)
        res['telphone']=set(telphoneL)
        res['url']=set(urlL)
        res['weichat']=set(weichatL)
        result.append(res)
    return result

def downloadDetailInfo(request):
    logger.warning("qing qiu page......")
    wordMd5=request.GET.get('filenameMd5')

    tmps=customBuildDetailInfo(wordMd5)
    wb = xlwt.Workbook(encoding='utf-8')
    ws = wb.add_sheet('联系信息')
    ws.write(0, 0, 'QQ')
    ws.write(0, 1, '邮箱')
    ws.write(0, 2, '地址')
    ws.write(0, 3, '手机')
    ws.write(0, 4, '电话')
    ws.write(0, 5, '网址')
    ws.write(0, 6, '微信')
    #
    excel_row = 1

    for tmp in tmps:
        try:
            ws.write(excel_row, 0, ";".join(tmp['qq']))
            ws.write(excel_row, 1, ";".join(tmp['email']))
            ws.write(excel_row, 2, ";".join(tmp['address']))
            ws.write(excel_row, 3, ";".join(tmp['mobilphone']))
            ws.write(excel_row, 4, ";".join(tmp['telphone']))
            ws.write(excel_row, 5, ";".join(tmp['url']))
            ws.write(excel_row, 6, ";".join(tmp['weichat']))
            excel_row = excel_row + 1
        except:
            continue
    #
    response = HttpResponse(content_type='application/vnd.ms-excel')
    response['Content-Disposition'] = 'attachment; filename=result.xls'
    wb.save(response)
    return response

def downloadCustomFenkuaiFile(request):
    parentMd5=request.GET.get('filenameMd5')
    targetDir=customInfoDir+"\\"+parentMd5
    manyCompanyDir=os.listdir(targetDir)  #多个分块文件信息

    catalogJson=cache.get(parentMd5)
    if catalogJson!=None:
        catalog=json.loads(catalogJson)

    guodu={}
    for value in catalog.values():
        guodu[value[-1]]=value[0]

    temp = tempfile.TemporaryFile()
    archive = zipfile.ZipFile(temp, 'w', zipfile.ZIP_DEFLATED)
    #
    for each in manyCompanyDir:
        archive.write(customInfoDir+"\\"+parentMd5+"\\"+each+"\\"+"fullInfo.txt",guodu[each]+u'.txt')
    archive.close()
    data=temp.tell()
    temp.seek(0)

    wrapper = FileWrapper(temp)
    response = HttpResponse(wrapper, content_type='application/zip')
    response['Content-Disposition'] = 'attachment; filename=test.zip'
    response['Content-Length'] = data
    return response

def downloadMiddleStep1_2(request):
    parentMd5=request.GET.get('filenameMd5')
    targetDir=customInfoDir+"\\"+parentMd5
    manyCompanyDir=os.listdir(targetDir)  #多个分块文件信息

    catalogJson=cache.get(parentMd5)
    if catalogJson!=None:
        catalog=json.loads(catalogJson)
    guodu={}
    for value in catalog.values():
        guodu[value[-1]]=value[0]

    temp = tempfile.TemporaryFile()
    archive = zipfile.ZipFile(temp, 'w', zipfile.ZIP_DEFLATED)
    #
    for each in manyCompanyDir:
        archive.write(customInfoDir+"\\"+parentMd5+"\\"+each+"\\"+"step1-2.txt",guodu[each]+u'.txt')
    archive.close()
    data=temp.tell()
    temp.seek(0)

    wrapper = FileWrapper(temp)
    response = HttpResponse(wrapper, content_type='application/zip')
    response['Content-Disposition'] = 'attachment; filename=step1-2.zip'
    response['Content-Length'] = data
    return response

def downloadMiddleStep1_3(request):
    parentMd5=request.GET.get('filenameMd5')
    targetDir=customInfoDir+"\\"+parentMd5
    manyCompanyDir=os.listdir(targetDir)  #多个分块文件信息

    catalogJson=cache.get(parentMd5)
    if catalogJson!=None:
        catalog=json.loads(catalogJson)
    guodu={}
    for value in catalog.values():
        guodu[value[-1]]=value[0]

    temp = tempfile.TemporaryFile()
    archive = zipfile.ZipFile(temp, 'w', zipfile.ZIP_DEFLATED)
    #
    for each in manyCompanyDir:
        archive.write(customInfoDir+"\\"+parentMd5+"\\"+each+"\\"+"step1-3.txt",guodu[each]+u'.txt')
    archive.close()
    data=temp.tell()
    temp.seek(0)

    wrapper = FileWrapper(temp)
    response = HttpResponse(wrapper, content_type='application/zip')
    response['Content-Disposition'] = 'attachment; filename=step1-3.zip'
    response['Content-Length'] = data
    return response

def downloadMiddleStep1_4(request):
    parentMd5=request.GET.get('filenameMd5')
    targetDir=customInfoDir+"\\"+parentMd5
    manyCompanyDir=os.listdir(targetDir)  #多个分块文件信息

    catalogJson=cache.get(parentMd5)
    if catalogJson!=None:
        catalog=json.loads(catalogJson)
    guodu={}
    for value in catalog.values():
        guodu[value[-1]]=value[0]

    temp = tempfile.TemporaryFile()
    archive = zipfile.ZipFile(temp, 'w', zipfile.ZIP_DEFLATED)
    #
    for each in manyCompanyDir:
        archive.write(customInfoDir+"\\"+parentMd5+"\\"+each+"\\"+"step1-4.txt",guodu[each]+u'.txt')
    archive.close()
    data=temp.tell()
    temp.seek(0)

    wrapper = FileWrapper(temp)
    response = HttpResponse(wrapper, content_type='application/zip')
    response['Content-Disposition'] = 'attachment; filename=step1-4.zip'
    response['Content-Length'] = data
    return response

def downloadMiddleStep1_5(request):
    parentMd5=request.GET.get('filenameMd5')
    targetDir=customInfoDir+"\\"+parentMd5
    manyCompanyDir=os.listdir(targetDir)  #多个分块文件信息

    catalogJson=cache.get(parentMd5)
    if catalogJson!=None:
        catalog=json.loads(catalogJson)
    guodu={}
    for value in catalog.values():
        guodu[value[-1]]=value[0]

    temp = tempfile.TemporaryFile()
    archive = zipfile.ZipFile(temp, 'w', zipfile.ZIP_DEFLATED)
    #
    for each in manyCompanyDir:
        archive.write(customInfoDir+"\\"+parentMd5+"\\"+each+"\\"+"step1-5.txt",guodu[each]+u'.txt')
    archive.close()
    data=temp.tell()
    temp.seek(0)

    wrapper = FileWrapper(temp)
    response = HttpResponse(wrapper, content_type='application/zip')
    response['Content-Disposition'] = 'attachment; filename=step1-5.zip'
    response['Content-Length'] = data
    return response


def downloadCustomFenPianFile(request):
    parentMd5=request.GET.get('filenameMd5')

    catalogJson=cache.get(parentMd5)
    if catalogJson!=None:
        catalog=json.loads(catalogJson)

    # return HttpResponse('ok')

    catalog=json.loads(catalogJson)
    sourceDir=customInfoDir+"\\"+parentMd5
    #进行复制操作
    targetDir=customInfoDirTemp+"\\"+parentMd5
    shutil.copytree(sourceDir,targetDir,ignore=shutil.ignore_patterns('fullInfo.txt','*companyName.txt','*step*.txt'))
    # 对文件夹进行重命名
    # [0]表示名字,[1]表示md5
    for value in catalog.values():
        os.rename(os.path.join(targetDir,value[1]),os.path.join(targetDir,value[0]))

    utilities = ZipUtilities()
    utilities.toZip(targetDir,u"自定义格式分片文件")
    response = StreamingHttpResponse(utilities.zip_file, content_type='application/zip')
    response['Content-Disposition'] = 'attachment; filename=temp.zip'
    return response

def contactHandler(request):
    filenameMd5=request.GET.get("filenameMd5")
    tmp=customBuildInfoResult(filenameMd5)
    return render_to_response('marsplan/contactresult.html',{'filenameMd5':filenameMd5,'contactInfo':tmp})

def companyNameHandler(request):
    filenameMd5=request.GET.get("filenameMd5")
    tmp=customBuildNameInfoResult(filenameMd5)
    return render_to_response('marsplan/companynameresult.html',{'filenameMd5':filenameMd5,'companyInfo':tmp})

def customBuildNameInfoResult(wordMd5):
    wordDir=customInfoDir
    targetDir=wordDir+"\\"+wordMd5
    manyCompanyDir=os.listdir(targetDir)

    result=[]
    for eachDir in manyCompanyDir:
        eachCompanyDir=targetDir+"\\"+eachDir
        fileList=os.listdir(eachCompanyDir)      #表示一个数据块中有多少个联系方式单元
        companyNameL=companyName(eachCompanyDir,fileList,eachDir)
        res={}
        res['id']=eachDir
        res['companyName']=showOne(companyNameL)
        result.append(res)
    return result

def customBuildNameDetailInfoResult(wordMd5):
    wordDir=customInfoDir
    targetDir=wordDir+"\\"+wordMd5
    manyCompanyDir=os.listdir(targetDir)

    result=[]
    for eachDir in manyCompanyDir:
        eachCompanyDir=targetDir+"\\"+eachDir
        fileList=os.listdir(eachCompanyDir)      #表示一个数据块中有多少个联系方式单元
        companyNameL=companyName(eachCompanyDir,fileList,eachDir)
        res={}
        res['id']=eachDir
        res['companyName']=set(companyNameL)
        result.append(res)
    return result

def downloadNameInfo(request):
    wordMd5=request.GET.get('filenameMd5')

    tmps=customBuildNameDetailInfoResult(wordMd5)
    wb = xlwt.Workbook(encoding='utf-8')
    ws = wb.add_sheet('企业名称信息')
    ws.write(0, 0, 'Id')
    ws.write(0, 1, '企业名称')
    excel_row = 1

    for tmp in tmps:
        try:
            ws.write(excel_row, 0, tmp['id'])
            ws.write(excel_row, 1, ";".join(tmp['companyName']))
            excel_row = excel_row + 1
        except:
            continue
    #
    response = HttpResponse(content_type='application/vnd.ms-excel')
    response['Content-Disposition'] = 'attachment; filename=公司名称.xls'
    wb.save(response)
    return response

def downloadNameFenpianFile(request):
    parentMd5=request.GET.get('filenameMd5')
    targetDir=customInfoDir+"\\"+parentMd5
    manyCompanyDir=os.listdir(targetDir)  #多个分块文件信息

    catalogJson=cache.get(parentMd5)
    if catalogJson!=None:
        catalog=json.loads(catalogJson)

    guodu={}
    for value in catalog.values():
        guodu[value[-1]]=value[0]

    temp = tempfile.TemporaryFile()
    archive = zipfile.ZipFile(temp, 'w', zipfile.ZIP_DEFLATED)
    #
    for each in manyCompanyDir:
        archive.write(customInfoDir+"\\"+parentMd5+"\\"+each+"\\"+each+"companyName.txt",guodu[each]+u'.txt')
    archive.close()
    data=temp.tell()
    temp.seek(0)

    wrapper = FileWrapper(temp)
    response = HttpResponse(wrapper, content_type='application/zip')
    response['Content-Disposition'] = 'attachment; filename=companyName.zip'
    response['Content-Length'] = data
    return response
    # return HttpResponse('Ok')

def showOne(target):
    if len(target)!=0:
        return target[0]
    else:
        return ""